package getsubs.popnapisi;

import getsubs.model.SubtitleFinder;
import java.io.*;
import java.net.*;
import java.util.*;

public class PopnSubtitleFinder implements SubtitleFinder {
    private final String root;
    private final Web web;
    private final UrlOpener urlOpener;
    
    public PopnSubtitleFinder(String root, Web web, UrlOpener urlOpener) {
        this.root = root;
        this.web = web;
        this.urlOpener = urlOpener;
    }


    /**
     * @throws IOException when fail to communicate with http://sub-titles.net
     */
    public List<PopnSubtitle> findSubtitlesFor(String showname,
                                           String season,
                                           String episode)
           throws IOException
    {
        String url = subtitleListUrl(showname, season, episode);
        String page = web.GET(url);
        List<String> subLinks = findAllSubtitlesLink(page);

        List<PopnSubtitle> result = new ArrayList();
        for(String link:subLinks) {
            result.add(createSubtitleFromLink(link));
        }
        return result;
    }

    static List<String> findAllSubtitlesLink(CharSequence page) {
        List<String> result = new ArrayList<String>();

        SubsInfoMatcher matcher = SubsInfoMatcher.createFor(page);
        while (matcher.find()) {
            result.add(matcher.getRelativeLink());
        }

        return result;
    }

    static String subtitleListUrl(String showName,
                                         String season,
                                         String episode)
    {
        try {
            return "http://sub-titles.net/ppodnapisi/search?"
                    + "tbsl=3&"
                    + "asdp=1&"
                    + "sK=" + URLEncoder.encode(showName, "UTF-8") + "&"
                    + "sJ=9&"
                    + "sO=desc&"
                    + "sS=movie&"
                    + "submit=Search&"
                    + "sAKA=1&"
                    + "sTS=" + URLEncoder.encode(season, "UTF-8") + "&"
                    + "sTE=" + URLEncoder.encode(episode, "UTF-8") + "&"
                    + "sY=&"
                    + "sR=&"
                    + "sT=1";
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    public PopnSubtitle createSubtitleFromLink(String link) {
        return new PopnSubtitle(root + link, this.urlOpener);
    }
}
